<?php
namespace App\Repos;
use App\Models\Client;
use App\Models\ClientCar;
use DB;

class ClientRepo 
{
    public static function store($data)
    {
    	$rs['status'] = false;
    	$client = array_only($data,['code','name','phone']);
    	DB::beginTransaction();
    	try {
    		$flag = Client::firstOrCreate(['name'=>$client['name']],$client);

	    	if($data['car_num'][0]) {
	    		foreach ($data['car_num'] as $k => $v) {
                    $hascar = ClientCar::where(['car_num'=>$v])->first();
                    if($hascar) continue;
                    $car['client_id'] = $flag->id;
	    			$car['car_num'] = $v;
	    			$car['car_brand_id'] = $data['car_brand_id'][$k];
	    			$car['car_serie_id'] = $data['car_serie_id'][$k];
                    $car['car_model_id'] = array_get($data,'car_model_id'.$k);
	    			$car['engine_num']   = $data['engine_num'][$k];
	    			$car['vin']          = $data['vin'][$k];
	    			$car['car_type_id']  = $data['car_type_id'][$k];
	    			ClientCar::create($car);
	    		}
	    	}
    		
    	} catch (\Exception $e) {
    		DB::rollBack();
    		$rs['msg'] = $e->getMessage();
    		return $rs;
    	}
    	$rs['status'] = true;
    	DB::commit(); 	

    	return $rs;
    }

    public static function destroy($id)
    {
        $rs['status'] = false;
        $car_num = ClientCar::where(['client_id'=>$id])->count();
        if($car_num>0) {
            $rs['msg'] = '请先删除客户的'.$car_num.'条车辆信息';
            return $rs;
        }
        Client::destroy($id);
        $rs['status'] = true;
        return $rs;
    }
}
